#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
直接执行校准数据结构转换
"""

import json
import os
from datetime import datetime

# 读取原始文件
input_file = "calibration_data_20250825_180643.json"

print(f"开始转换 {input_file}...")

try:
    # 读取原始数据
    with open(input_file, 'r', encoding='utf-8') as f:
        original_data = json.load(f)
    
    print(f"原始数据包含 {len(original_data)} 个衰减设置")
    
    # 转换数据结构
    converted_data = {}
    total_points = 0
    
    # 从 [attenuation][frequency] = loss 转换为 [frequency][attenuation] = loss
    for attenuation_str, frequency_data in original_data.items():
        for frequency_str, loss_value in frequency_data.items():
            if frequency_str not in converted_data:
                converted_data[frequency_str] = {}
            
            converted_data[frequency_str][attenuation_str] = loss_value
            total_points += 1
    
    print(f"转换完成，总共 {total_points} 个数据点")
    print(f"频率点数: {len(converted_data)}")
    
    # 创建备份
    backup_file = input_file.replace('.json', '_backup.json')
    with open(backup_file, 'w', encoding='utf-8') as f:
        json.dump(original_data, f, indent=2, ensure_ascii=False)
    print(f"备份文件已创建: {backup_file}")
    
    # 准备输出数据
    output_data = {
        "metadata": {
            "structure": "frequency_attenuation", 
            "description": "数据结构: [frequency][attenuation] = loss",
            "converted_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "total_frequencies": len(converted_data),
            "total_data_points": total_points
        },
        "calibration_data": converted_data
    }
    
    # 保存转换后的数据
    with open(input_file, 'w', encoding='utf-8') as f:
        json.dump(output_data, f, indent=2, ensure_ascii=False)
    
    print("✅ 转换成功完成!")
    print(f"新结构: [frequency][attenuation] = loss")
    
    # 显示示例
    sample_freq = list(converted_data.keys())[0]
    sample_att = list(converted_data[sample_freq].keys())[0]
    sample_value = converted_data[sample_freq][sample_att]
    print(f"示例: [{sample_freq}][{sample_att}] = {sample_value}")
    
except Exception as e:
    print(f"转换失败: {str(e)}")